package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.User;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.vo.CountsVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.service.UserApi;
import com.tanhua.autoconfig.template.SendSmsTemplate;
import com.tanhua.service.UserLikeApi;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.checkerframework.checker.units.qual.A;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author げっしょく
 * @date 2021/10/21
 */
@Service
public class UserService{

    private String Au = "Check";


    @Autowired
    private SendSmsTemplate sendSms;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private UserLikeApi userLikeApi;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    /**
     * 登录，发送验证码，并将验证码存入redis
     * @param phone 手机号码
     */
    public void sendMsg(String phone) {
        String code = "123456";
        //String code = RandomStringUtils.randomNumeric(6);
        //sendSms.sendSms(phone, code);
        redisTemplate.opsForValue().set(Au + phone, code, 5, TimeUnit.MINUTES);
    }

    /**
     * 校验验证码
     * @param phone 用户的手机号码
     * @param verificationCode 用户输入的验证码
     * @return 返回用户是否是新用户和token字符串
     */
    public Map loginVerification(String phone, String verificationCode) {
        String code = redisTemplate.opsForValue().get(Au + phone);
        if (code == null || !verificationCode.equals(code)) {
            throw new BusinessException(ErrorResult.loginError());
        }
        boolean isNew = false;
        redisTemplate.delete(Au + phone);
        User user = userApi.getByPhone(phone);
        String type = "0101";
        if (user == null) {
            type = "0102";
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long id = userApi.save(user);
            user.setId(id);

            isNew = true;
            String hx = "hx" + user.getId();
            Boolean aBoolean = huanXinTemplate.addContact(hx, "123456");
            if (aBoolean) {
                user.setHxUser(hx);
                user.setHxPassword("123456");
                userApi.update(user);
            }
        }
        mqMessageService.sendLogService(user.getId(), type, "user", null);
        //6、通过JWT生成token(存入id和手机号码)
        Map tokenMap = new HashMap();
        tokenMap.put("id",user.getId());
        tokenMap.put("mobile",phone);
        String token = JwtUtils.getToken(tokenMap);
        //7、构造返回值
        Map retMap = new HashMap();
        retMap.put("token",token);
        retMap.put("isNew",isNew);

        return retMap;

    }


    public CountsVo counts() {
        //获得当前用户id
        Long id = UserHolder.getId();
        //通过redis查看我点了喜欢的用户id
        Set<String> likes = redisTemplate.opsForSet().members(Constants.USER_LIKE_KEY + id);
        //通过redis查到的用户id查看我是否在他们的喜欢列表里面
        Integer count = 0;
        for (String like : likes) {
            if (redisTemplate.opsForSet().isMember(Constants.USER_LIKE_KEY + like, id.toString())) {
                //如果在就将计数器+1
                count++;
            }
        }
        //通过数据库查找喜欢我的有多少人
        List<UserLike> likeMes = userLikeApi.getLikeMe(id);
        CountsVo countsVo = new CountsVo();
        countsVo.setEachLoveCount(count);
        countsVo.setLoveCount(likes.size());
        //判断喜欢我的是否为空
        if (CollUtil.isEmpty(likeMes)) {
            countsVo.setFanCount(0);
        } else {
            countsVo.setFanCount(likeMes.size());
        }
        return countsVo;
    }
}
